import os, sys
import subprocess

import mimetypes

from damn.util import GetScriptPath, RunBlenderURI, BlenderDependency

BlenderDependency()


from damn.analyzer import AnalyzerFileException, AnalyzerUnknownTypeException, AnalyzerException
from damn import AnalyzerInstance, FileReference, AssetReference

from damn.analyzer import BaseAnalyzer
class BlendAnalyzer(BaseAnalyzer):
  handled_types = ["application/x-blender"]

  def analyze(self, anURI):
    f = FileReference(anURI)
    stdoutdata, stderrdata, returncode = RunBlenderURI(anURI, GetScriptPath(__file__))
    
    print 'OUTPUT:', stdoutdata, stderrdata
    if returncode == -11:
      print 'BLENDER CRASH!'
    if returncode != 0: raise AnalyzerException('BlendAnalyzer failed with %s'%(returncode))
    
    try:
      data = stdoutdata.split('----')[1].replace('\n', '').replace('\r', '')
    except:
      print("E: BlendAnalyzer: parsing output for file", anURI, '\n', stdoutdata.decode("utf-8"), stderrdata.decode("utf-8"))
      return f
      
    data = eval(data)
    
    externalFileReferences = []
    def GetFile(fileName):
      for fi in externalFileReferences:
        if fi.fileName == fileName:
          return fi
    
    for tex, info in data['textures'].items():
      if not info['packed']:
        if info['fileName'] != '' and tex != 'Render Result':
          try:
            ref = AnalyzerInstance().AnalyzeFile(info['fileName'])
          except (AnalyzerUnknownTypeException, AnalyzerFileException):
            ref = FileReference(info['fileName'])
            ref.brokenReference = True
            a = AssetReference(tex, "texture", ref)
          externalFileReferences.append(ref)
      else:
        print("I: BlendAnalyzer: Packed", tex)
        a = AssetReference(tex, "application/x-blender.image", f)
        for n, v in info['metadata'].items():
          a.AddMetaData(n, v)
     
    for mesh, info in data['objects'].items(): 
      a = AssetReference(mesh, "application/x-blender.object", f)
      for tex, path in info['dependencies']['T'].items():
        print "DEPENDENCY", tex, path
        d = None
        if path:
          fi = GetFile(path)
          if fi:
            print("I: BlendAnalyzer: External image", fi, path)
            d = fi.GetAsset(os.path.basename(path))
        else:
          print("I: BlendAnalyzer: Packed image", tex, path)
          d = f.GetAsset(tex, "application/x-blender.image")
        if d:
          a.AddDepency(d)
        else:
          print("E: BlendAnalyzer: dependency not found", tex, path)
          
      for n, v in info['metadata'].items():
        a.AddMetaData(n, v)
      
    return f




















